<template>
    <div class="app-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <el-button link @click="goBack">
                    <el-icon><Back /></el-icon>
                    <span>返回商品列表</span>
                </el-button>
                <h2 class="title">编辑商品</h2>
            </div>
        </div>

        <!-- 表单内容 -->
        <div class="form-container">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                <!-- 基本信息 -->
                <div class="form-section">
                    <div class="section-header">
                        <el-divider content-position="left">基本信息</el-divider>
                    </div>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="商品名称" prop="productsName">
                                <el-input v-model="form.productsName" placeholder="请输入商品名称" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="商品分类" prop="categoryId">
                                <el-cascader
                                            v-model="form.categoryId"
                                            :options="categoryOptions"
                                            :props="{
                                                checkStrictly: true,
                                                label: 'name',
                                                value: 'id',
                                                emitPath: false
                                            }"
                                            placeholder="请选择商品分类"
                                            clearable
                                            class="w-full"
                                        />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="商品状态" prop="status">
                                <el-select v-model="form.status" placeholder="请选择商品状态" class="w-full">
                                    <el-option 
                                        v-for="dict in product_status"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="存储条件" prop="storageCondition">
                                <el-select v-model="form.storageCondition" placeholder="请选择存储条件" class="w-full">
                                    <el-option 
                                        v-for="dict in product_storage_condition"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="保质期(天)" prop="shelfLife">
                                <el-input-number v-model="form.shelfLife" :min="1" :max="999" class="w-full" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="产地" prop="origin">
                                <el-cascader
                                            v-model="form.origin"
                                            :options="regionOptions"
                                            :props="{
                                                expandTrigger: 'hover',
                                                label: 'areaName',
                                                value: 'areaId',
                                                children: 'children'
                                            }"
                                            placeholder="请选择产地"
                                            class="w-full"
                                        />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item label="商品描述" prop="description">
                        <el-input
                            v-model="form.description"
                            type="textarea"
                            :rows="4"
                            placeholder="请输入商品描述"
                        />
                    </el-form-item>
                </div>

                <!-- 商品图片 -->
                <div class="form-section">
                    <div class="section-header">
                        <el-divider content-position="left">商品图片</el-divider>
                    </div>
                    <el-form-item label="主图" prop="mainImage" required>
                        <div class="product-uploader">
                            <el-upload
                                class="avatar-uploader"
                                :show-file-list="false"
                                :before-upload="beforeImageUpload"
                                :action="uploadUrl"
                                :headers="headers"
                            >
                                <img v-if="form.mainImage" :src="form.mainImage" class="uploaded-image">
                                <div v-else class="upload-placeholder">
                                    <el-icon><Plus /></el-icon>
                                    <div class="upload-text">点击上传主图</div>
                                </div>
                            </el-upload>
                            <div class="upload-tip">建议尺寸：800x800px，支持jpg、png格式</div>
                        </div>
                    </el-form-item>

                    <el-form-item label="图集" prop="images">
                        <div class="product-uploader-list">
                            <el-upload
                                :file-list="form.images"
                                list-type="picture-card"
                                :action="uploadUrl"
                                :headers="headers"
                                :before-upload="beforeImageUpload"
                                :on-success="handleImageSuccess"
                                :on-remove="handleRemove"
                                :on-preview="handlePictureCardPreview"
                                multiple
                                :limit="5"
                            >
                                <el-icon><Plus /></el-icon>
                            </el-upload>
                        </div>
                        <div class="upload-tip">最多上传5张图片，建议尺寸：800x800px</div>
                    </el-form-item>
                </div>

                <!-- 规格设置 -->
                <div class="form-section">
                    <div class="section-header">
                        <el-divider content-position="left">规格设置</el-divider>
                    </div>
                    <el-form-item>
                        <el-button type="primary" @click="handleSpecSettings">
                            <el-icon><Setting /></el-icon>
                            设置规格
                        </el-button>
                        <div class="upload-tip">点击设置商品规格，用于生成SKU</div>
                    </el-form-item>
                </div>

                <!-- SKU管理 -->
                <div class="form-section">
                    <div class="section-header">
                        <el-divider content-position="left">SKU管理</el-divider>
                    </div>
                    <el-form-item>
                        <el-button type="primary" @click="handleSkuManage">
                            <el-icon><Goods /></el-icon>
                            管理SKU
                        </el-button>
                        <div class="upload-tip">点击管理商品SKU，设置价格和库存</div>
                    </el-form-item>
                </div>

                <!-- 表单操作 -->
                <div class="form-actions">
                    <el-button @click="goBack">取消</el-button>
                    <el-button type="primary" @click="submitForm">保存</el-button>
                </div>
            </el-form>
        </div>

        <!-- 图片预览对话框 -->
        <el-dialog v-model="previewVisible" title="预览图片">
            <img :src="previewUrl" alt="Preview Image" style="width: 100%" />
        </el-dialog>
    </div>
</template>

<script setup name="ProductEdit">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Back, Plus, Setting, Goods } from '@element-plus/icons-vue';
import { getSystemArea } from '@/api/system/common.js';
import { getToken } from '@/utils/auth';
import { listCategoriesCli } from '@/api/farmer/categories';
import { useDict } from '@/utils/dict';
import { useProductStore } from '@/store/modules/product';

const route = useRoute();
const router = useRouter();
const formRef = ref();
const productStore = useProductStore();

// 获取字典数据
const { product_storage_condition, product_status } = useDict('product_storage_condition', 'product_status');

// 上传相关配置
const uploadUrl = import.meta.env.VITE_APP_BASE_API + "/common/upload";
const headers = { Authorization: 'Bearer ' + getToken() };

// 分类数据
const categoryOptions = ref([]);

// 表单数据，使用 store 中的数据
const form = ref({ ...productStore.productInfo });

// 表单验证规则
const rules = {
    productsName: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    categoryId: [
        { required: true, message: '请选择商品分类', trigger: 'change' }
    ],
    status: [
        { required: true, message: '请选择商品状态', trigger: 'change' }
    ],
    storageCondition: [
        { required: true, message: '请选择存储条件', trigger: 'change' }
    ],
    shelfLife: [
        { required: true, message: '请输入保质期', trigger: 'blur' }
    ],
    origin: [
        { required: true, message: '请选择产地', trigger: 'change' }
    ],
    description: [
        { required: true, message: '请输入商品描述', trigger: 'blur' },
        { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
    ]
};

// Mock地区数据
const regionOptions = ref([]);

const listRegions = async () => {
    const res = await getSystemArea()
    regionOptions.value = res.data
}

// 获取商品详情
const getProductDetail = async (id) => {
    try {
        await productStore.loadProductDetail(id);
        // 使用 store 中的数据更新表单
        form.value = { ...productStore.productInfo };
    } catch (error) {
        console.error('获取商品详情失败：', error);
        ElMessage.error('获取商品详情失败');
    }
};

const beforeImageUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isImage) {
        ElMessage.error('只能上传图片文件!');
        return false;
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!');
        return false;
    }
    return true;
};

// 图片预览
const previewVisible = ref(false);
const previewUrl = ref('');

// 处理图片上传成功
const handleImageSuccess = (res, file) => {
    if (res.code === 200) {
        form.value.images.push({ url: res.url });
        ElMessage.success('上传成功');
    } else {
        ElMessage.error('上传失败');
    }
};

// 处理图片移除
const handleRemove = (file) => {
    const index = form.value.images.findIndex(item => item.url === file.url);
    if (index !== -1) {
        form.value.images.splice(index, 1);
    }
};

// 处理图片预览
const handlePictureCardPreview = (file) => {
    previewUrl.value = file.url;
    previewVisible.value = true;
};

// 路由跳转方法
const goBack = () => router.push('/products/manager');
const handleSpecSettings = () => router.push(`/products/specs/${route.params.id}`);
const handleSkuManage = () => router.push(`/products/sku/${route.params.id}`);

// 表单提交
const submitForm = async () => {
    if (!formRef.value) return;
    
    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // 更新 store 中的数据
                productStore.updateProductInfo(form.value);
                // 保存所有更改
                await productStore.saveAll();
                ElMessage.success('保存成功');
                goBack();
            } catch (error) {
                console.error('保存失败：', error);
                ElMessage.error('保存失败');
            }
        }
    });
};

const listCategorys = async () => {
    const res = await listCategoriesCli()
    categoryOptions.value = res.data
}

onMounted(() => {
    const productId = route.params.id;
    if (productId) {
        getProductDetail(productId);
    }
    listRegions();
    listCategorys();
});

</script>

<style lang="scss" scoped>
.app-container {
    padding: 16px;
    background-color: #fff;

    .page-header {
        margin-bottom: 24px;

        .header-content {
            display: flex;
            align-items: center;
            gap: 16px;

            .el-button {
                font-size: 14px;
                
                .el-icon {
                    margin-right: 4px;
                }
            }

            .title {
                font-size: 16px;
                font-weight: 500;
                color: #1f2f3d;
                color: var(--el-text-color-primary);
            }
        }
    }

    .form-container {
        .form-section {
            margin-bottom: 32px;

            .section-header {
                margin-bottom: 24px;

                :deep(.el-divider__text) {
                    font-size: 16px;
                    font-weight: 500;
                    color: var(--el-text-color-primary);
                }
            }
        }

        :deep(.el-form-item) {
            margin-bottom: 20px;

            .el-form-item__label {
                font-weight: 500;
                padding-right: 12px;
            }
        }

        .w-full {
            width: 100%;
        }

        .product-uploader {
            .uploaded-image {
                width: 200px;
                height: 200px;
                object-fit: cover;
                border-radius: 4px;
            }

            .upload-placeholder {
                width: 200px;
                height: 200px;
                border: 1px dashed var(--el-border-color);
                border-radius: 4px;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                cursor: pointer;
                transition: border-color 0.3s;

                &:hover {
                    border-color: var(--el-color-primary);

                    .el-icon {
                        color: var(--el-color-primary);
                    }
                }

                .el-icon {
                    font-size: 28px;
                    color: var(--el-text-color-secondary);
                    margin-bottom: 8px;
                }

                .upload-text {
                    font-size: 14px;
                    color: var(--el-text-color-secondary);
                }
            }
        }

        .product-uploader-list {
            :deep(.el-upload--picture-card) {
                width: 100px;
                height: 100px;
                line-height: 100px;
            }

            :deep(.el-upload-list__item) {
                width: 100px;
                height: 100px;
            }
        }

        .upload-tip {
            font-size: 12px;
            color: var(--el-text-color-secondary);
            margin-top: 8px;
            line-height: 1.4;
        }

        .form-actions {
            margin-top: 32px;
            padding-top: 24px;
            border-top: 1px solid var(--el-border-color-lighter);
            display: flex;
            justify-content: center;
            gap: 16px;

            .el-button {
                min-width: 120px;
            }
        }
    }
}
</style> 